#!/usr/bin/python

# cli.py

import sys
import os.path

from doctest_tools import setpath
ROOT_DIR = setpath.setpath(__file__, remove_first = True)[0]
#print "ROOT_DIR", ROOT_DIR

from naimath.engine import engine, question

diagnosis_limit = 6
question_limit = 6

def run(rule_base, canned_questions = None, recorded_answers = None):
    engine.init()
    #question.load_translations('en_IN', 'en_US')
    question.load_translations('en_US')

    answers = {'symptom': {}, 'sign': {}, 'investigation': {}}
    if canned_questions:
        nested_questions, top_level_questions = \
          question.read_canned_questions(canned_questions)
        ask_questions(top_level_questions, nested_questions, answers)

    while True:
        diagnosis, questions = engine.consult(rule_base, **answers)

        print
        print "diagnosis:"
        for i, (diagnosis, cf, _questions) \
         in enumerate(diagnosis[:diagnosis_limit]):
            print "  %d: %s, CF %.1f" % \
                    (i + 1, question.diagnosis(diagnosis), cf)

        print
        print "questions:"
        for i, (category, q_name, relevance_score) \
         in enumerate(questions[:question_limit]):
            print "  %d: %s, weight %.1f" % \
                    (i + 1, question.lookup(category, q_name).question,
                     relevance_score)

        if not questions:
            print "  No questions left"
        else:
            print
            q = ask("Which question would you like to answer? ",
                    question_limit) \
                - 1
            category, q_name = questions[q][:2]
            answers[category][q_name] = question.lookup(category, q_name).ask()

def ask_questions(questions, nested_questions, answers):
    for cat, quest in questions:
        if quest not in answers[cat]:
            print
            ans = question.lookup(cat, quest).ask()
            answers[cat][quest] = ans
            if (cat, quest) in nested_questions:
                ans_map = nested_questions[cat, quest]
                if ans in ans_map:
                    ask_questions(ans_map[ans], nested_questions, answers)

def ask(prompt, limit, special = None):
    while True:
        try:
            ans = raw_input(prompt)
            if special is not None and ans.lower() == special:
                return 0
            d = int(ans)
            if 0 < d <= limit:
                return d
        except ValueError:
            pass
        print "Illegal answer: enter a number between 1 and", limit

def usage():
    sys.stderr.write("usage: cli.py rule_base\n")
    sys.exit(2)

if __name__ == "__main__":
    #print "sys.argv", sys.argv
    if len(sys.argv) != 2: usage()
    run(sys.argv[1], os.path.join(ROOT_DIR, 'naimath', 'engine',
                                  sys.argv[1] + '.canned'))
